<template>
  <div class="hr-flow-container">
    <h1>人事一条龙流程</h1>

    <!-- 流程步骤 -->
    <el-steps :active="activeStep" finish-status="success" simple>
      <el-step title="员工入职" />
      <el-step title="考勤管理" />
    </el-steps>

    <!-- 员工入职 -->
    <div v-show="activeStep === 1" class="step-content">
      <el-card>
        <el-form :model="employeeForm" :rules="employeeRules" ref="employeeFormRef" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="employeeForm.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="employeeForm.gender" placeholder="请选择性别">
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部门" prop="departmentId">
                <el-select v-model.number="employeeForm.departmentId" placeholder="请选择部门">
                  <el-option v-for="d in departmentList" :key="d.id" :label="d.name" :value="d.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职日期" prop="hireDate">
                <el-date-picker v-model="employeeForm.hireDate" type="date" placeholder="请选择入职日期" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电话" prop="phone">
                <el-input v-model="employeeForm.phone" placeholder="请输入电话" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-button type="primary" @click="submitEmployee">提交入职</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 考勤管理 -->
    <div v-show="activeStep === 2" class="step-content">
      <el-card>
        <el-form :model="attendanceForm" :rules="attendanceRules" ref="attendanceFormRef" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="员工" prop="employeeId">
                <el-select v-model.number="attendanceForm.employeeId" placeholder="请选择员工">
                  <el-option v-for="e in employeeList" :key="e.id" :label="e.name" :value="e.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考勤日期" prop="date">
                <el-date-picker v-model="attendanceForm.date" type="date" placeholder="请选择日期" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="上班时间" prop="checkInTime">
                <el-time-picker v-model="attendanceForm.checkInTime" placeholder="请选择上班时间" style="width: 100%" value-format="HH:mm:ss" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下班时间" prop="checkOutTime">
                <el-time-picker v-model="attendanceForm.checkOutTime" placeholder="请选择下班时间" style="width: 100%" value-format="HH:mm:ss" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-button type="primary" @click="submitAttendance">提交考勤</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import employeeApi from '../api/employeeapi.js';
import departmentApi from '../api/departmentapi.js';
import attendanceApi from '../api/attendanceApi.js';

// 步骤控制
const activeStep = ref(1);

// 表单
const employeeFormRef = ref(null);
const attendanceFormRef = ref(null);

const employeeForm = reactive({
  name: '',
  gender: '',
  departmentId: '',
  hireDate: '',
  phone: ''
});

const attendanceForm = reactive({
  employeeId: '',
  date: '',
  checkInTime: '',
  checkOutTime: ''
});

// 验证规则
const employeeRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  hireDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }]
};

const attendanceRules = {
  employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
  date: [{ required: true, message: '请选择考勤日期', trigger: 'change' }]
};

// 列表
const departmentList = ref([]);
const employeeList = ref([]);

// 加载部门
const loadDepartments = async () => {
  try {
    const res = await departmentApi.list(); // 不传参数
    if (res.code === 200) departmentList.value = res.data;
    else departmentList.value = [];
  } catch (err) {
    departmentList.value = [];
    console.error('部门接口异常', err);
  }
};

// HumanResourceFlow.vue
const loadEmployees = async () => {
  try {
    const res = await employeeApi.list(); // <-- 改成 list()，不是 all()
    if (res.code === 200) employeeList.value = res.data;
    else employeeList.value = [];
  } catch (err) {
    employeeList.value = [];
    console.error('员工接口异常', err);
  }
};


// 员工入职提交
const submitEmployee = async () => {
  if (!employeeFormRef.value) return;
  await employeeFormRef.value.validate(async (valid) => {
    if (!valid) return;
    const formData = {
      ...employeeForm,
      hireDate: employeeForm.hireDate ? new Date(employeeForm.hireDate).toISOString().split('T')[0] : null,
      isDeleted: 0,
      status: 1
    };
    // 确保日期字段格式正确
    if (formData.hireDate) {
      formData.hireDate = new Date(formData.hireDate).getTime();
    }
    // 确保departmentId是数字类型
    if (formData.departmentId) {
      formData.departmentId = Number(formData.departmentId);
    }
    try {
      const res = await employeeApi.add(formData);
      if (res.code === 200) {
        ElMessage.success('员工入职成功');
        await loadEmployees(); // 自动刷新员工列表
        activeStep.value = 2; // 跳到考勤
      } else ElMessage.error(res.msg || '员工入职失败');
    } catch (err) {
      ElMessage.error('员工入职接口异常');
      console.error(err);
    }
  });
};

// 考勤提交
const submitAttendance = async () => {
  if (!attendanceFormRef.value) return;
  await attendanceFormRef.value.validate(async (valid) => {
    if (!valid) return;
    const formData = {
      employee_id: attendanceForm.employeeId,
      date: attendanceForm.date ? new Date(attendanceForm.date).toISOString().split('T')[0] : '',
      check_in_time: attendanceForm.checkInTime,
      check_out_time: attendanceForm.checkOutTime,
      is_deleted: 0
    };
    try {
      const res = await attendanceApi.add(formData);
      if (res.code === 200) {
        ElMessage.success('考勤记录提交成功');
        activeStep.value = 3;
      } else ElMessage.error(res.msg || '考勤提交失败');
    } catch (err) {
      ElMessage.error('考勤接口异常');
      console.error(err);
    }
  });
};




// 初始化
onMounted(() => {
  loadDepartments();
  loadEmployees(); // 调用 list() 加载员工
});

</script>

<style scoped>
.hr-flow-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
.step-content {
  margin-top: 20px;
}
</style>




